package org.liveboardgames.agricola.view.component
{
    import org.liveboardgames.agricola.model.enums.ResourceTypeEnum;
    import org.liveboardgames.common.dictionary.collections.HashCollection;
    
    import mx.events.DragEvent;
    import mx.managers.DragManager;
    
    public class ResourceBox extends ResourceDisplayer
    {
        public function ResourceBox()
        {
            super();
            this.addEventListener(DragEvent.DRAG_ENTER, onDragEnter);
            this.addEventListener(DragEvent.DRAG_DROP, onDragDrop);
            this.addEventListener(DragEvent.DRAG_COMPLETE, onDragComplete);
            this.setStyle("backgroundAlpha", "0.5");
            this.setStyle("backgroundImage", "assets/images/common/wooden_background.jpeg");
        }
        
        protected function onDragEnter(event:DragEvent):void
        {
            var dropTarget:ResourceBox = event.currentTarget as ResourceBox;
            DragManager.acceptDragDrop(dropTarget);
        }
        
        protected function onDragDrop(event:DragEvent):void
        {
            DragManager.showFeedback(DragManager.MOVE);
            
            if (event.dragSource.hasFormat('resource'))
            {
                var resourceImage:ResourceImage = ResourceImage(event.dragSource.dataForFormat('resource'));
                var resourceType:String = resourceImage.resourceType;
                var quantity:int = resourceImage.quantity;
                
                this.addResource(resourceType, quantity);
            }
        }
        
        protected function getResourceAsMap(resourceType:ResourceTypeEnum, quantity:int):HashCollection
        {
            var resourceAsMap:HashCollection = null;
            
            if (quantity > 0 && resourceType != null)
            {
                resourceAsMap = new HashCollection();
                resourceAsMap.put(resourceType, quantity);
            }
            
            return resourceAsMap;
        }
        
        protected function onDragComplete(event:DragEvent):void
        {
            if (event.action == DragManager.MOVE)
            {
                var target:ResourceBox = ResourceBox(event.currentTarget);
                
                var resourceImage:ResourceImage = ResourceImage(event.dragSource.dataForFormat('resource'));
                var resourceType:String = resourceImage.resourceType;
                var quantity:int = resourceImage.quantity;
                
                removeAnimal(resourceType, quantity);
            }
        }
        
        public function removeAnimal(resource:String, quantity:int):void
        {
            var currentQuantity:int = this.resources.getValue(resource) as int;
            this.resources.put(resource, Math.max(0, currentQuantity - quantity));
        }
    }
}